package cn.foolishbird.crow.spring.security;

import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;

import java.io.Serializable;
import java.util.Objects;
import java.util.Set;

/**
 *
 * @author foolish bird
 **/
public class SuperAdminPermissionEvaluator implements PermissionEvaluator {

    /**
     * 超级管理员角色名
     */
    private final String roleAdmin;

    public SuperAdminPermissionEvaluator(String roleAdmin) {
        this.roleAdmin = roleAdmin;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        Set<String> permissionSet = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
        boolean superAdmin = permissionSet.stream().filter(Objects::nonNull)
                .anyMatch(r -> Objects.equals(this.roleAdmin, r));
        return superAdmin || permissionSet.contains(permission.toString());
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        return false;
    }

}
